
// pages/commit/commit.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressItemIsShow:false,
    addressData:[],
    address:'选择收货地址',
    productData:[],
    total:0,
    count:0,
    addressIndex:-1,
    ids:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  
    var ids = options.id.split("@")

    console.log('ids=>',ids)

    this.setData({
      ids:ids
    })

    this.getAddressData()
    this.getShopcart(ids)


  },
  toggleAddressItemIsShow:function(){
    this.setData({
      addressItemIsShow:!this.data.addressItemIsShow
    })
  },
  getAddressData:function(){

    wx.showLoading({
      title: '加载中...',
    })

    wx.cloud.callFunction({
      name:'get_address',
      success:res=>{
        wx.hideLoading()
        this.setData({
          addressData:res.result.data
        })
      },
      fail:error=>{
        wx.hideLoading()
        console.log('云函数调用失败error=>',error)
      }
    })

  },
  selectAddress:function(e){


    var index = e.currentTarget.dataset.index

    var address = this.data.addressData[index].address + this.data.addressData[index].datel

    this.setData({
      addressIndex:index,
      address:address
    })


  },
  getShopcart:function(ids){

    wx.showLoading({
      title: '加载中...',
      icon:'none'
    })
    
    wx.cloud.callFunction({
      name:'get_shopcart_byids',
      data:{ids:ids},
      success:res=>{
        wx.hideLoading()
        this.setData({
          productData:res.result.data
        })
        console.log(res)

        var ids = []

        res.result.data.forEach(v=>{
          ids.push(v.id)
        })

        this.getProduct(ids)


      },
      fail:error=>{
        wx.hideLoading()
        console.log('云函数调用失败error=>',error)
      }

    })

  },
  getProduct:function(ids){
    wx.showLoading({
      title: '加载中...',
      icon:'none'
    })

    wx.cloud.callFunction({
      name:'get_product_byid',
      data:{ids:ids},
      success:res=>{
        wx.hideLoading()

        var total = 0

        var count = 0
        this.data.productData.forEach(v=>{


          res.result.data.forEach(x=>{
            if(v.id == x._id){

              v.img = x.small_img
              v.price = x.price
              v.name = x.name
            
            }
          })

          total += v.price * v.count

          count += v.count

        })


        this.setData({
          productData:this.data.productData,
          total:total,
          count:count
        })

        



      },
      fail:error=>{
        wx.hideLoading()
        console.log("云函数调用失败error=>",error)
      }
    })
  },

  addOrder:function(item,id){
    wx.showLoading({
      title:'加载中...',
      icon:'none',
      duration:2000
    })

    wx.cloud.callFunction({
      name:'add_order',
      data:item,
      success:res=>{

        wx.hideLoading()
        console.log("新增订单成功=>",res)
        this.removeShopcart(id)

      },
      fail:error=>{
        wx.hideLoading()
        console.log('云函数调用失败error=>',error)
      }
    })
  },
  removeShopcart:function(id){

    wx.showLoading({
      title: '加载中...',
      icon:'none'
    })

    wx.cloud.callFunction({
      name:'remove_shopcart_byid',
      data:{
        ids:id
      },
      success:res=>{
        wx.hideLoading()
        console.log('删除购物车成功==>',res)
      },
      fail:error=>{
        wx.hideLoading()
        console.log('云函数调用失败error=>',error)
      }
    })


  },

  //提交订单
  commit:function(){

    if(this.data.addressIndex === -1){

      wx.showToast({
        title: '请选择地址',
        icon:'none',
        duration:2000
      })

      return;
    }

    var address = this.data.addressData[this.data.addressIndex]

    var userAddress = {

      address:address.address + address.datel,
      phone:address.phone,
      user:address.user,
    }

    wx.showLoading({
      title: '加载中...',
      icon:'none'
    })

    var ids = this.data.ids

    wx.cloud.callFunction({
      name:'get_shopcart_byids',
      data:{
        ids:ids,
      },
      success:res=>{

        console.log('res==>',res)

        //获取商品id

        var orderShopcart = res.result.data

        var proudctIds = []

        orderShopcart.forEach(v=>{

          if(proudctIds.indexOf(v.id) == -1){

            proudctIds.push(v.id)
          }

        })


        //获取商品数据

        wx.cloud.callFunction({
          name:'get_product_byid',
          data:{
            ids:proudctIds,
          },
          success:res=>{

            wx.hideLoading()

            var orderNo = 'No' + new Date().getTime()

            var dateTime = this.formatDateTime(new Date())

            console.log('dateTime==>',dateTime)

            var orderItem = {

              id:orderNo,
              userAddress:userAddress,
              product:[],
              dateTime:dateTime,

            }

            
            var count = 0

            var total = 0

            orderShopcart.forEach(v=>{

             var order = {

                
                count:v.count,
                rule:v.rule,
                productId:v.id,
  
              }

              count += v.count

              res.result.data.forEach(x=>{

                if(v.id = x._id){

                  order.img = x.small_img

                  order.price = x.price

                  order.name = x.name
 

                }

              })

              total += order.count * order.price


              orderItem.product.push(order)

            })

            orderItem.count = count

            orderItem.total = total


            this.addOrder(orderItem,this.data.ids)

            wx.switchTab({
              url: '../order/order',
            })

          },
          fail:error=>{

            wx.hideLoading()

            console.log('云函数调用失败==>',error)

          }
        })



      },
      fail:error=>{
        console.log('云函数调用失败==>',error)
      }
    })



  },
  formatDateTime:function (date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h=h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    var second=date.getSeconds();
    second=second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
},

 
})